# Standard libraries
import wsgiref.handlers

# AppEngine imports
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import logging
import os
import json
from models import WorldCupData, WorldCupStatistics, PredictionData

class Prediction(webapp.RequestHandler):

  def RenderJS(self, filename, dictionary):
    """Render the given template definition file with the given dictionary.

    Args:
      filename: The filename of the template to expand.
      dict: The dictionary that contains the values to populate in the template.
    """
    path = os.path.join(os.path.dirname(__file__), filename)
    self.response.headers['Content-Type'] = 'text/javascript'
    self.response.out.write(template.render(path, dictionary))

  def GetPred(self):
    pred = {}
    pred['1'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['2'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['3'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['4'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['5'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['6'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['7'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['8'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['9'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['10'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['11'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['12'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['13'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['14'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['15'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['16'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['17'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['18'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['19'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['20'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['21'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['22'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['23'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['24'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['25'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['26'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['27'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['28'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['29'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['30'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['31'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['32'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['33'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['34'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['35'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['36'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['37'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['38'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['39'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['40'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['41'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['42'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['43'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['44'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['45'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['46'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['47'] = {'team1': 0, 'team2': 0, 'draw': 0}
    pred['48'] = {'team1': 0, 'team2': 0, 'draw': 0}
    return pred

  def SavePrediction(self):
    user_id = self.request.get('userId')
    match_id = int(self.request.get('matchId'))
    fav_team = self.request.get(user_id + ':favorite')
    logging.error(user_id + ':' + str(match_id) + ':' + fav_team)
    old_fav = 0
    cur_fav = int(fav_team)

    #try:
    results = WorldCupData.gql("WHERE user_id = :1 and match_id = :2", user_id, match_id)
    new_item = True
    for row in results:
      new_item = False
      item = row
      old_fav = int(row.fav_team)

    if (old_fav == cur_fav):
      return

    if new_item:
      item = WorldCupData()

    item.user_id = user_id
    item.match_id = match_id
    item.fav_team = fav_team
    item.put()
    self.SaveStatistics(match_id, old_fav, cur_fav)
    self.response.out.write(json.write({'error': '0'}))


    #except:
    #  self.response.out.write(json.write({'error': '1'}))


  def GetPrediction(self):
    query = WorldCupStatistics.all()
    pred = {}
    for item in query:
      match_id = item.match_id
      match = {}
      match['team1'] = item.team1_count
      match['team2'] = item.team2_count
      match['draw'] = item.draw_count
      match['match'] = match_id
      pred[match_id] = match
    pred['data'] = json.write(pred)
    logging.error(pred)

    self.RenderJS('templates/predict.js', pred)


  def getMatchData(self):
    predictionData = {"56":{"team2_count":0,"draw_count":0,"user_id":"raheel.farooq01@googlewave.com","match_id":"9","team1_count":1},"54":{"team2_count":0,"draw_count":0,"user_id":"finnster@googlewave.com","match_id":"9","team1_count":1},"42":{"team2_count":0,"draw_count":1,"user_id":"julioalmeida@googlewave.com","match_id":"9","team1_count":0},"48":{"team2_count":0,"draw_count":0,"user_id":"shadowfiltro@googlewave.com","match_id":"9","team1_count":2},"43":{"team2_count":0,"draw_count":0,"user_id":"adriaans.mark@googlewave.com","match_id":"9","team1_count":4},"60":{"team2_count":0,"draw_count":0,"user_id":"chrisdewit@googlewave.com","match_id":"9","team1_count":7},"61":{"team2_count":0,"draw_count":0,"user_id":"baecke@googlewave.com","match_id":"9","team1_count":6},"62":{"team2_count":1,"draw_count":0,"user_id":"alexbadila@googlewave.com","match_id":"9","team1_count":0},"63":{"team2_count":2,"draw_count":0,"user_id":"anjakhansen@googlewave.com","match_id":"9","team1_count":0},"64":{"team2_count":0,"draw_count":0,"user_id":"sarzen91@googlewave.com","match_id":"9","team1_count":5},"49":{"team2_count":1,"draw_count":0,"user_id":"pepijnherman@googlewave.com","match_id":"9","team1_count":0},"66":{"team2_count":0,"draw_count":0,"user_id":"glandman@googlewave.com","match_id":"9","team1_count":2},"67":{"team2_count":0,"draw_count":0,"user_id":"lizbethkaye@googlewave.com","match_id":"9","team1_count":2},"68":{"team2_count":0,"draw_count":0,"user_id":"raydark98@googlewave.com","match_id":"9","team1_count":6},"69":{"team2_count":0,"draw_count":0,"user_id":"wasim.ahmad121@googlewave.com","match_id":"9","team1_count":2},"52":{"team2_count":0,"draw_count":0,"user_id":"qasim.askari@googlewave.com","match_id":"9","team1_count":1},"53":{"team2_count":0,"draw_count":0,"user_id":"rgg.graham@googlewave.com","match_id":"9","team1_count":1},"24":{"team2_count":0,"draw_count":0,"user_id":"cjvanzwol@googlewave.com","match_id":"9","team1_count":2},"25":{"team2_count":0,"draw_count":0,"user_id":"timmatser@googlewave.com","match_id":"9","team1_count":1},"26":{"team2_count":0,"draw_count":0,"user_id":"alt148@googlewave.com","match_id":"9","team1_count":1},"27":{"team2_count":0,"draw_count":0,"user_id":"willemjanmaaskant@googlewave.com","match_id":"9","team1_count":1},"20":{"team2_count":0,"draw_count":0,"user_id":"richardosinga@googlewave.com","match_id":"9","team1_count":6},"21":{"team2_count":0,"draw_count":0,"user_id":"hpharmsen@googlewave.com","match_id":"9","team1_count":1},"22":{"team2_count":0,"draw_count":0,"user_id":"steen.knudsen@googlewave.com","match_id":"9","team1_count":1},"23":{"team2_count":0,"draw_count":0,"user_id":"acidjunk@googlewave.com","match_id":"9","team1_count":2},"46":{"team2_count":0,"draw_count":0,"user_id":"hassan.zeeshan@googlewave.com","match_id":"9","team1_count":2},"47":{"team2_count":0,"draw_count":0,"user_id":"tuxion@googlewave.com","match_id":"9","team1_count":4},"44":{"team2_count":0,"draw_count":0,"user_id":"thijs.drumont@googlewave.com","match_id":"9","team1_count":9},"45":{"team2_count":0,"draw_count":0,"user_id":"amianderssonaa@googlewave.com","match_id":"9","team1_count":1},"28":{"team2_count":0,"draw_count":0,"user_id":"tonjafabritz@googlewave.com","match_id":"9","team1_count":8},"29":{"team2_count":0,"draw_count":0,"user_id":"jordos222@googlewave.com","match_id":"9","team1_count":2},"40":{"team2_count":0,"draw_count":0,"user_id":"pols@sbaw.nl","match_id":"9","team1_count":8},"41":{"team2_count":0,"draw_count":0,"user_id":"rootvirtual@googlewave.com","match_id":"9","team1_count":1},"1":{"team2_count":0,"draw_count":0,"user_id":"gertbraun@googlewave.com","match_id":"9","team1_count":7},"3":{"team2_count":1,"draw_count":0,"user_id":"janpolsen@googlewave.com","match_id":"9","team1_count":0},"2":{"team2_count":0,"draw_count":0,"user_id":"judithvpuffelen@googlewave.com","match_id":"9","team1_count":3},"5":{"team2_count":0,"draw_count":0,"user_id":"rgallius@googlewave.com","match_id":"9","team1_count":1},"4":{"team2_count":0,"draw_count":0,"user_id":"fpoppelaars@googlewave.com","match_id":"9","team1_count":1},"7":{"team2_count":0,"draw_count":0,"user_id":"adrianklingen@googlewave.com","match_id":"9","team1_count":2},"6":{"team2_count":0,"draw_count":0,"user_id":"s.roodhorst@googlewave.com","match_id":"9","team1_count":1},"9":{"team2_count":0,"draw_count":1,"user_id":"kometen@googlewave.com","match_id":"9","team1_count":0},"8":{"team2_count":0,"draw_count":0,"user_id":"laurens.lammers@googlewave.com","match_id":"9","team1_count":5},"51":{"team2_count":0,"draw_count":2,"user_id":"rauwerda.peterpaul@googlewave.com","match_id":"9","team1_count":0},"39":{"team2_count":0,"draw_count":0,"user_id":"riskid@googlewave.com","match_id":"9","team1_count":3},"65":{"team2_count":0,"draw_count":0,"user_id":"andrus.ashoo@googlewave.com","match_id":"9","team1_count":1},"38":{"team2_count":0,"draw_count":0,"user_id":"robinvanotterdijk@googlewave.com","match_id":"9","team1_count":5},"70":{"team2_count":0,"draw_count":0,"user_id":"haraldbotn@googlewave.com","match_id":"9","team1_count":2},"59":{"team2_count":0,"draw_count":0,"user_id":"carlosrogue@googlewave.com","match_id":"9","team1_count":1},"58":{"team2_count":0,"draw_count":0,"user_id":"batanerc@googlewave.com","match_id":"9","team1_count":4},"11":{"team2_count":0,"draw_count":0,"user_id":"rvanderputte@googlewave.com","match_id":"9","team1_count":1},"10":{"team2_count":0,"draw_count":0,"user_id":"dannyfriedmann@googlewave.com","match_id":"9","team1_count":2},"13":{"team2_count":0,"draw_count":0,"user_id":"samyrahakbauw@googlewave.com","match_id":"9","team1_count":1},"12":{"team2_count":0,"draw_count":1,"user_id":"janineterlouw@googlewave.com","match_id":"9","team1_count":3},"15":{"team2_count":0,"draw_count":1,"user_id":"vic.knijper.poppelaars@googlewave.com","match_id":"9","team1_count":0},"14":{"team2_count":0,"draw_count":0,"user_id":"azizfatkh@googlewave.com","match_id":"9","team1_count":1},"17":{"team2_count":0,"draw_count":0,"user_id":"brewbart@googlewave.com","match_id":"9","team1_count":4},"16":{"team2_count":0,"draw_count":0,"user_id":"redboer@googlewave.com","match_id":"9","team1_count":3},"19":{"team2_count":0,"draw_count":0,"user_id":"hertoghs@googlewave.com","match_id":"9","team1_count":1},"18":{"team2_count":0,"draw_count":1,"user_id":"douwe.osinga@googlewave.com","match_id":"9","team1_count":0},"31":{"team2_count":0,"draw_count":0,"user_id":"thoriversen@googlewave.com","match_id":"9","team1_count":1},"30":{"team2_count":0,"draw_count":1,"user_id":"thepurple8@googlewave.com","match_id":"9","team1_count":0},"37":{"team2_count":0,"draw_count":0,"user_id":"macasal@googlewave.com","match_id":"9","team1_count":1},"36":{"team2_count":0,"draw_count":0,"user_id":"carlier.baptiste@googlewave.com","match_id":"9","team1_count":1},"35":{"team2_count":0,"draw_count":0,"user_id":"ck.jemian@googlewave.com","match_id":"9","team1_count":1},"34":{"team2_count":0,"draw_count":0,"user_id":"saarck@googlewave.com","match_id":"9","team1_count":3},"33":{"team2_count":0,"draw_count":0,"user_id":"mikob267@googlewave.com","match_id":"9","team1_count":1},"55":{"team2_count":0,"draw_count":0,"user_id":"jone.nyborg@googlewave.com","match_id":"9","team1_count":1},"32":{"team2_count":1,"draw_count":0,"user_id":"10pund@googlewave.com","match_id":"9","team1_count":0},"57":{"team2_count":0,"draw_count":0,"user_id":"zubair.shahid@googlewave.com","match_id":"9","team1_count":3},"50":{"team2_count":0,"draw_count":1,"user_id":"alban.deubeda@googlewave.com","match_id":"9","team1_count":0}}
    return predictionData
  def updateData(self, data, match_id):
    #match_id = 9

    #data = self.getMatchData()
    team1_counter = 0
    team2_counter = 0
    draw_counter = 0
    logging.error(match_id)
    logging.error(data)

    for key in data:
      world_cup_item = WorldCupData()
      if int(data[key]['team1_count']) > 0:
        world_cup_item.fav_team = '1'
        team1_counter = team1_counter + 1
      elif int(data[key]['team2_count']) > 0:
        world_cup_item.fav_team = '2'
        team2_counter = team2_counter + 1
      elif int(data[key]['draw_count']) > 0:
        world_cup_item.fav_team = '3'
        draw_counter = draw_counter + 1
      else:
        pass
      world_cup_item.match_id = match_id
      world_cup_item.user_id = data[key]['user_id']
      world_cup_item.put()

    if team1_counter == 0 and team2_counter == 0 and draw_counter == 0:
      return

    results = WorldCupStatistics.gql('WHERE match_id = :1', match_id)
    for item in results:
      item.team1_count = team1_counter
      item.team2_count = team2_counter
      item.draw_count = draw_counter
      item.match_id = match_id
      item.put()
    self.response.out.write('Done for match: ' + str(match_id) + ' successfully.')

  """Handles requests to /databse URLs."""
  def get(self):
    """Ensure that the user is an admin, then invoke appropriate action."""
    if self.request.path.startswith('/getprediction'):
      self.GetPrediction()
    if self.request.path.startswith('/saveprediction'):
      self.SavePrediction()
    if self.request.path.startswith('/updatedata'):
      self.updateData()


  def post(self):
    self.get()

